package org.geektimes.projects.user.web.controller;

import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.repository.DatabaseUserRepository;
import org.geektimes.projects.user.repository.InMemoryUserRepository;
import org.geektimes.projects.user.repository.UserRepository;
import org.geektimes.projects.user.sql.DBConnectionManager;
import org.geektimes.web.mvc.controller.PageController;
import sun.plugin.util.UIUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Map;
import java.util.UUID;

/**
 * @author: fengabner
 * @date: 2021/3/2 22:24
 * @version: 1.0
 * @description:
 */
@Path("/user")
public class UserController implements PageController {
    @POST
    @Path("/register")
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        User user = new User();
        user.setEmail(request.getParameter("email"));
        user.setPassword(request.getParameter("password"));
        DBConnectionManager dbConnectionManager = new DBConnectionManager();
        UserRepository userRepository = new DatabaseUserRepository(dbConnectionManager);
        try {
            boolean result = userRepository.save(user);
            if (result) {
                request.setAttribute("name", user.getEmail());
                return "success.jsp";
            }
            request.setAttribute("errorInfo", "该用户已存在，请重新注册");
        } catch (Exception e) {
            request.setAttribute("errorInfo", "系统异常，请联系平台");
        }

        return "error.jsp";
    }
}
